package link.chengguo.orangemall.single.pms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import link.chengguo.orangemall.annotation.IgnoreAuth;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.pms.entity.PmsGifts;
import link.chengguo.orangemall.pms.entity.PmsProduct;
import link.chengguo.orangemall.pms.service.IPmsFavoriteService;
import link.chengguo.orangemall.pms.service.IPmsGiftsService;
import link.chengguo.orangemall.pms.service.IPmsProductService;
import link.chengguo.orangemall.pms.vo.GoodsDetailResult;
import link.chengguo.orangemall.single.ApiBaseAction;
import link.chengguo.orangemall.sms.entity.SmsFlashPromotionProductRelation;
import link.chengguo.orangemall.sms.entity.SmsGroup;
import link.chengguo.orangemall.sms.entity.SmsGroupMember;
import link.chengguo.orangemall.sms.mapper.SmsGroupMapper;
import link.chengguo.orangemall.sms.mapper.SmsGroupMemberMapper;
import link.chengguo.orangemall.sms.service.ISmsFlashPromotionProductRelationService;
import link.chengguo.orangemall.sms.service.ISmsGroupService;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.service.IUmsMemberService;
import link.chengguo.orangemall.util.DateUtils;
import link.chengguo.orangemall.util.JsonUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import link.chengguo.orangemall.vo.Rediskey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品信息
 * </p>
 *
 * @author chengguo
 * @since 2019-04-19
 */
@RestController
@Slf4j
@Api(tags = "商品信息管理", description = "ProductController")
@RequestMapping("/api/pms/product")
public class ProductController extends ApiBaseAction {
    @Resource
    private IPmsProductService pmsProductService;
    @Autowired
    private IUmsMemberService memberService;
    @Autowired
    private IPmsFavoriteService favoriteService;
    @Resource
    private SmsGroupMemberMapper groupMemberMapper;
    @Resource
    private IPmsGiftsService giftsService;
    @Resource
    private ISmsGroupService groupService;
    @Resource
    private SmsGroupMapper groupMapper;
    @Autowired
    private ISmsFlashPromotionProductRelationService smsFlashPromotionProductRelationService;

    @SysLog(MODULE = "pms", REMARK = "根据条件分页查询所有商品信息列表")
    @ApiOperation("根据条件查询所有商品信息列表")
    @GetMapping(value = "/list")
    public Object getPmsProductByPage(PmsProduct entity,
                                      @RequestParam(value = "sortName",defaultValue = "create_time") String sortName,
                                      @RequestParam(value = "sortType", defaultValue = "0") Integer sortType,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize

    ) {

        try {
            IPage<PmsProduct> page = null;
            QueryWrapper queryWrapper=new QueryWrapper();
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name",entity.getKeyword());
            }
            queryWrapper.ne("special_type",1);//不是线下包装袋
            queryWrapper.eq("publish_status",1);//已上架
            queryWrapper.eq("verify_status",1);//审核通过
            if(entity.getCityCode()!=null){
                queryWrapper.eq("city_code",entity.getCityCode());
            }
            if (entity.getShopId()!=null){
                queryWrapper.eq("shop_id",entity.getShopId());
            }
            if (entity.getType()!=null){
                queryWrapper.eq("type",entity.getType());
            }
            if (entity.getProductCategoryId()!=null){
                queryWrapper.eq("product_category_id",entity.getProductCategoryId());
            }

            if (entity.getCategoryId()!=null){
                queryWrapper.eq("category_id",entity.getCategoryId());
            }

            if (sortType==0){
                queryWrapper.orderByDesc("create_time");
            }else if (ValidatorUtils.notEmpty(sortName)){
                if (sortType==1){
                    queryWrapper.orderByDesc(sortName);
                }else{
                    queryWrapper.orderByAsc(sortName);
                }
            }
            //商品关键字搜索
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name", entity.getKeyword());
            }
            log.info("已进入getPmsProductByPage，开始访问商品信息列表");
            page = pmsProductService.page(new Page<>(pageNum, pageSize),queryWrapper);
            return new CommonResult().success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有商品信息列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "pms", REMARK = "根据条件分页查询所有商品信息列表")
    @ApiOperation("根据条件查询所有商品信息列表")
    @GetMapping(value = "/listForCategory")
    public Object getPmsProductlistForCategory(PmsProduct entity,Integer[] categoryIds,
                                      @RequestParam(value = "sortName", defaultValue = "create_time") String sortName,
                                      @RequestParam(value = "sortType", defaultValue = "0") Integer sortType,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize

    ) {
        try {
            IPage<PmsProduct> page = null;
            QueryWrapper queryWrapper=new QueryWrapper();
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name",entity.getKeyword());
            }
//            不等于<>
            queryWrapper.ne("special_type",1);//不是线下包装
            queryWrapper.eq("publish_status",1);//已上架
            queryWrapper.eq("verify_status",1);//审核通过
            if(entity.getCityCode()!=null){
                queryWrapper.eq("city_code",entity.getCityCode());
            }

            if (entity.getShopId()!=null){
                queryWrapper.eq("shop_id",entity.getShopId());
            }
            if (entity.getType()!=null){
                queryWrapper.eq("type",entity.getType());
            }
            if (entity.getProductCategoryId()!=null){
                queryWrapper.eq("product_category_id",entity.getProductCategoryId());
            }

            if (categoryIds!=null && categoryIds.length>0){
                queryWrapper.in("category_id",categoryIds);
                //	IN 查询,查询多种状态值
            }

            if (sortType==0){
                queryWrapper.orderByDesc("create_time");
            }else if (ValidatorUtils.notEmpty(sortName)){
                if (sortType==1){
                    queryWrapper.orderByDesc(sortName);
                }else{
                    queryWrapper.orderByAsc(sortName);
                }
            }
            //商品关键字搜索
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name", entity.getKeyword());
            }

            page = pmsProductService.page(new Page<>(pageNum, pageSize),queryWrapper);
            return new CommonResult().success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件查询所有商品信息列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "pms", REMARK = "根据条件分页查询所有包装列表")
    @ApiOperation("根据条件分页查询所有包装列表")
    @GetMapping(value = "/listPackages")
    public Object listPackages(PmsProduct entity,
                                      @RequestParam(value = "sortName", defaultValue = "create_time") String sortName,
                                      @RequestParam(value = "sortType", defaultValue = "0") Integer sortType) {
        try {
            List<PmsProduct> list = null;
            QueryWrapper queryWrapper=new QueryWrapper(entity);
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name",entity.getKeyword());
            }
            queryWrapper.eq("city_code",entity.getCityCode());
            if (entity.getShopId()!=null){
                queryWrapper.eq("shop_id",entity.getShopId());
            }
            if (sortType==0){
                queryWrapper.orderByDesc("create_time");
            }else if (ValidatorUtils.notEmpty(sortName)){
                if (sortType==1){
                    queryWrapper.orderByDesc(sortName);
                }else{
                    queryWrapper.orderByAsc(sortName);
                }
            }
            //商品关键字搜索
            if (ValidatorUtils.notEmpty(entity.getKeyword())){
                queryWrapper.like("name", entity.getKeyword());
            }

            list = pmsProductService.list(queryWrapper);
            return new CommonResult().success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据条件分页查询所有包装列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "pms", REMARK = "查询商品规格信息")
    @IgnoreAuth
    @GetMapping(value = "/getSkuById")
    @ApiOperation(value = "查询商品规格信息")
    public Object getSkuById(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        GoodsDetailResult goods = null;
        try {
            goods = JsonUtils.jsonToPojo(redisService.get(String.format(Rediskey.GOODSDETAILSKU, id + "")), GoodsDetailResult.class);
            if (ValidatorUtils.empty(goods) || ValidatorUtils.empty(goods.getGoods())) {
                log.info("redis缓存失效：" + id);
                goods = pmsProductService.getGoodsSku(id);
                redisService.set(String.format(Rediskey.GOODSDETAILSKU, id + ""), JsonUtils.objectToJson(goods));
            }
        } catch (Exception e) {
            log.info("redis缓存失效：" + id);
            goods = pmsProductService.getGoodsRedisById(id);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        return new CommonResult().success(map);
    }


    @SysLog(MODULE = "pms", REMARK = "查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/normal/detail")
    @ApiOperation(value = "查询商品详情信息")
    public Object queryProductDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        GoodsDetailResult goods = null;
        try {
            goods = JsonUtils.jsonToPojo(redisService.get(String.format(Rediskey.GOODSDETAIL, id + "")), GoodsDetailResult.class);
            if (ValidatorUtils.empty(goods) || ValidatorUtils.empty(goods.getGoods())) {
                log.info("redis缓存失效：" + id);
                goods = pmsProductService.getGoodsRedisById(id);
                redisService.set(String.format(Rediskey.GOODSDETAIL, id + ""), JsonUtils.objectToJson(goods));
            }
        } catch (Exception e) {
            log.info("redis缓存失效：" + id);
            goods = pmsProductService.getGoodsRedisById(id);
        }
        Map<String, Object> map = new HashMap<>();

        UmsMember umsMember = null;
        try{
            umsMember = memberService.getNewCurrentMember();
        }catch (Exception e){
        }
        if (umsMember != null && umsMember.getId() != null) {
           boolean collected= pmsProductService.ifGoodsCollected(id,umsMember.getId());
           map.put("favorite", collected);
        }
        //记录浏览量到redis,然后定时更新到数据库
        recordGoodsFoot(id);
        map.put("goods", goods);
        return new CommonResult().success(map);
    }


    @SysLog(MODULE = "pms", REMARK = "根据条码查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/code/detail")
    @ApiOperation(value = "根据条码查询商品详情信息")
    public Object codeDetail(String cityCode,Long shopId,String barcode) {
        GoodsDetailResult goods = null;
        try {
            goods = JsonUtils.jsonToPojo(redisService.get( String.format(Rediskey.GOODSDETAILBYCODE, barcode + "")), GoodsDetailResult.class);
            if (ValidatorUtils.empty(goods) || ValidatorUtils.empty(goods.getGoods())) {
                log.info("redis缓存失效：" + barcode);
                goods = pmsProductService.getGoodsRedisByCode(cityCode,shopId,barcode);
                redisService.set( String.format(Rediskey.GOODSDETAIL, barcode + ""), JsonUtils.objectToJson(goods));
            }
        } catch (Exception e) {
            log.info("redis缓存失效：" + barcode);
            goods = pmsProductService.getGoodsRedisByCode(cityCode,shopId,barcode);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        return new CommonResult().success(map);
    }



    @SysLog(MODULE = "pms", REMARK = "查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/paimai/detail")
    @ApiOperation(value = "查询商品详情信息")
    public Object queryPaiMaiProductDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        Map<String,Object> map=pmsProductService.queryPaiMaigoodsDetail(id);
        return new CommonResult().success(map);
    }

    @SysLog(MODULE = "pms", REMARK = "查询团购商品列表")
    @IgnoreAuth
    @ApiOperation(value = "查询团购商品列表")
    @GetMapping(value = "/groupHotGoods/list")
    public Object groupHotGoods(PmsProduct product,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        List<SmsGroup> groupList = groupService.list(new QueryWrapper<>());
        List<SmsGroup> result = new ArrayList<>();
        for (SmsGroup group : groupList) {
            if (ValidatorUtils.empty(group.getHours())) {
                continue;
            }
            Long nowT = System.currentTimeMillis();
            Date endTime = DateUtils.convertStringToDate(DateUtils.addHours(group.getEndTime(), group.getHours()), "yyyy-MM-dd HH:mm:ss");
            if (nowT > group.getStartTime().getTime() && nowT < endTime.getTime()) {
                PmsProduct g = pmsProductService.getById(group.getGoodsId());
                if (g != null) {
                    group.setGoods(g);
                    result.add(group);
                }
            }
        }
        return new CommonResult().success(result);
    }

    @SysLog(MODULE = "pms", REMARK = "查询团购商品列表")
    @IgnoreAuth
    @ApiOperation(value = "查询团购商品列表")
    @GetMapping(value = "/groupGoods/list")
    public Object groupGoodsList(PmsProduct product,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                 @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        List<SmsGroup> groupList = groupService.list(new QueryWrapper<>());
        if (groupList != null && groupList.size() > 0) {
            List<Long> ids = groupList.stream()
                    .map(SmsGroup::getGoodsId)
                    .collect(Collectors.toList());
            product.setPublishStatus(1);
            product.setVerifyStatus(1);
            product.setMemberId(null);
            IPage<PmsProduct> list = pmsProductService.page(new Page<PmsProduct>(pageNum, pageSize), new QueryWrapper<>(product).in("id", ids));
            return new CommonResult().success(list);
        }
        return null;
    }

    @SysLog(MODULE = "pms", REMARK = "查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/goodsGroup/detail")
    @ApiOperation(value = "查询商品详情信息")
    public Object groupGoodsDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        //记录浏览量到redis,然后定时更新到数据库

        GoodsDetailResult goods = null;
        try {
            goods = JsonUtils.jsonToPojo(redisService.get(String.format(Rediskey.GOODSDETAIL, id + "")), GoodsDetailResult.class);
            if (ValidatorUtils.empty(goods)) {
                log.info("redis缓存失效：" + id);
                goods = pmsProductService.getGoodsRedisById(id);
            }
        } catch (Exception e) {
            log.info("redis缓存失效：" + id);
            goods = pmsProductService.getGoodsRedisById(id);
            e.printStackTrace();
        }
        SmsGroup group = groupMapper.getByGoodsId(id);
        Map<String, Object> map = new HashMap<>();
        UmsMember umsMember = memberService.getNewCurrentMember();
        if (umsMember != null && umsMember.getId() != null) {
            boolean collected= pmsProductService.ifGoodsCollected(id,umsMember.getId());
            map.put("favorite", collected);
        }
        if (group != null) {
            map.put("memberGroupList", groupMemberMapper.selectList(new QueryWrapper<SmsGroupMember>().eq("group_id", group.getId())));
            map.put("group", group);
        }
        map.put("goods", goods);
        return new CommonResult().success(map);
    }


    @SysLog(MODULE = "pms", REMARK = "查询团购商品列表")
    @IgnoreAuth
    @ApiOperation(value = "查询礼物商品列表")
    @GetMapping(value = "/gift/list")
    public Object giftList(PmsGifts product,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                           @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        IPage<PmsGifts> list = giftsService.page(new Page<PmsGifts>(pageNum, pageSize), new QueryWrapper<>(product));
        return new CommonResult().success(list);

    }

    @SysLog(MODULE = "pms", REMARK = "查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/secskill/detail")
    @ApiOperation(value = "查询商品详情信息")
    public Object secskillDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        //记录浏览量到redis,然后定时更新到数据库
        SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(id);
        GoodsDetailResult goods = null;
        try {
            goods = JsonUtils.jsonToPojo(redisService.get(String.format(Rediskey.GOODSDETAIL, relation.getProductId() + "")), GoodsDetailResult.class);
            if (ValidatorUtils.empty(goods)) {
                log.info("redis缓存失效：" + relation.getProductId());
                goods = pmsProductService.getGoodsRedisById(relation.getProductId());
            }
        } catch (Exception e) {
            log.info("redis缓存失效：" + relation.getProductId());
            goods = pmsProductService.getGoodsRedisById(relation.getProductId());
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        UmsMember umsMember = memberService.getNewCurrentMember();
        if (umsMember != null && umsMember.getId() != null) {
            boolean collected= pmsProductService.ifGoodsCollected(id,umsMember.getId());
            map.put("favorite", collected);
        }
        map.put("skillDetail", relation);
        map.put("goods", goods);
        return new CommonResult().success(map);
    }

    @SysLog(MODULE = "pms", REMARK = "查询商品详情信息")
    @IgnoreAuth
    @GetMapping(value = "/gift/detail")
    @ApiOperation(value = "查询礼物商品详情信息")
    public Object giftDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        PmsGifts goods = giftsService.getById(id);
        Map<String, Object> map = new HashMap<>();
        UmsMember umsMember = memberService.getNewCurrentMember();
        if (umsMember != null && umsMember.getId() != null) {
            boolean collected= pmsProductService.ifGoodsCollected(id,umsMember.getId());
            map.put("favorite", collected);
        }
        map.put("goods", goods);
        return new CommonResult().success(map);
    }


    private Integer recordGoodsFoot(Long id) {
        //记录浏览量到redis,然后定时更新到数据库
        String key = Rediskey.GOODS_VIEWCOUNT_CODE + id;
        //找到redis中该篇文章的点赞数，如果不存在则向redis中添加一条
        Map<Object, Object> viewCountItem = redisUtil.hGetAll(Rediskey.GOODS_VIEWCOUNT_KEY);
        Integer viewCount = 0;
        if (!viewCountItem.isEmpty()) {
            if (viewCountItem.containsKey(key)) {
                viewCount = Integer.parseInt(viewCountItem.get(key).toString()) + 1;
                redisUtil.hPut(Rediskey.GOODS_VIEWCOUNT_KEY, key, viewCount + "");
            } else {
                redisUtil.hPut(Rediskey.GOODS_VIEWCOUNT_KEY, key, 1 + "");
            }
        } else {
            viewCount = 1;
            redisUtil.hPut(Rediskey.GOODS_VIEWCOUNT_KEY, key, 1 + "");
        }
        return viewCount;
    }

}
